package interfaz;

import java.awt.image.BufferedImage;
import java.io.File;
import java.util.HashMap;
import javax.imageio.ImageIO;
/*
 * ImageBuffer.java
 *
 * Created on 1 de marzo de 2008, 21:36
 *
 * To change this template, choose Tools | Template Manager
 * and open the template in the editor.
 */

/**
 *
 * @author victor
 */
public class ImageBuffer extends Thread {

    private static HashMap bufferImagenes = new HashMap();
    private static BufferedImage interrogante;
    private String cargarImagen;
    private BufferedImage buffer;
    public boolean loaded = false;

    /** Creates a new instance of ImageBuffer */
    public ImageBuffer(String path) {
        cargarImagen = path;
        buffer = interrogante;
    }

    public static void cargarInterrogante() {
        interrogante = loadImage("interrogante.jpg");
    }

    public static BufferedImage obtenerInterrogante() {
        return interrogante;
    }

    private static BufferedImage loadImage(String nombre) {

        File file = new File(nombre);
        try {
            return ImageIO.read(file);
        } catch (Exception e) {
            System.out.println("El error fue : " + 
                    e.getClass().getName() + " " + 
                    e.getMessage() + ": " + nombre);
            return null;
        }
    }

    //metodos para a xestion do buffer de imaxes
    public static void agregarBufferData(ImageBufferData image,
            String pathname) {
        if (bufferImagenes.size() < 10) {
            bufferImagenes.put(pathname, image);
        } else {
            String menosUsado = ImageBufferData.getLeastUsed(bufferImagenes);
            eliminarBuffer(menosUsado);
            bufferImagenes.put(pathname, image);
        }

    }

    public static void eliminarBuffer(String pathname) {
        bufferImagenes.remove(pathname);
    }

    public static BufferedImage obtenerBuffer(String pathname) {
        return ((ImageBufferData) bufferImagenes.get(pathname)).getBuffer();
    }

    public void run() {
        if (bufferImagenes.containsKey(cargarImagen)) {
            this.buffer = (BufferedImage) obtenerBuffer(cargarImagen);
        } else {
            BufferedImage bufferTmp = loadImage(cargarImagen);
            ImageBuffer.agregarBufferData(
                    new ImageBufferData(bufferTmp), cargarImagen);
            this.buffer = bufferTmp;
            loaded = true;
        }
    }

    public BufferedImage getBuffer() {
        return buffer;
    }
}
